import 'package:uuid/uuid.dart';

class Habit {
  final String id;
  final String name;
  final String description;
  final String icon;
  final int colorValue;
  final String frequency; // daily, weekly, etc.
  final String amount; // e.g., "10分钟", "8杯水"
  final List<DateTime> completedDates;
  final DateTime createdAt;
  final List<String> reminderTimes; // List of time strings in "HH:mm" format

  Habit({
    String? id,
    required this.name,
    this.description = '',
    this.icon = 'list',
    this.colorValue = 0xFF4A6572, // Default color
    this.frequency = '每天',
    this.amount = '',
    List<DateTime>? completedDates,
    DateTime? createdAt,
    List<String>? reminderTimes,
  })  : id = id ?? const Uuid().v4(),
        completedDates = completedDates ?? [],
        createdAt = createdAt ?? DateTime.now(),
        reminderTimes = reminderTimes ?? [];

  // Check if habit was completed today
  bool isCompletedToday() {
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    return completedDates.any((date) => 
      date.year == today.year && 
      date.month == today.month && 
      date.day == today.day
    );
  }

  // Get streak count (consecutive days completed)
  int getStreakCount() {
    if (completedDates.isEmpty) return 0;
    
    completedDates.sort();
    final now = DateTime.now();
    final today = DateTime(now.year, now.month, now.day);
    
    int streak = 0;
    DateTime checkDate = today;
    
    // Check backwards from today
    while (true) {
      if (completedDates.any((date) => 
        date.year == checkDate.year && 
        date.month == checkDate.month && 
        date.day == checkDate.day
      )) {
        streak++;
        checkDate = checkDate.subtract(const Duration(days: 1));
      } else {
        break;
      }
    }
    
    return streak;
  }

  // Create a copy of this habit with optional parameter changes
  Habit copyWith({
    String? name,
    String? description,
    String? icon,
    int? colorValue,
    String? frequency,
    String? amount,
    List<DateTime>? completedDates,
    List<String>? reminderTimes,
  }) {
    return Habit(
      id: this.id,
      name: name ?? this.name,
      description: description ?? this.description,
      icon: icon ?? this.icon,
      colorValue: colorValue ?? this.colorValue,
      frequency: frequency ?? this.frequency,
      amount: amount ?? this.amount,
      completedDates: completedDates ?? this.completedDates,
      createdAt: this.createdAt,
      reminderTimes: reminderTimes ?? this.reminderTimes,
    );
  }

  // Method to add a completed date
  Habit addCompletedDate(DateTime date) {
    // Normalize the date to remove time
    final normalizedDate = DateTime(date.year, date.month, date.day);
    
    // Check if this date is already recorded
    if (completedDates.any((d) => 
      d.year == normalizedDate.year && 
      d.month == normalizedDate.month && 
      d.day == normalizedDate.day
    )) {
      return this;
    }
    
    final newCompletedDates = List<DateTime>.from(completedDates)
      ..add(normalizedDate);
    
    return copyWith(completedDates: newCompletedDates);
  }

  // Method to remove a completed date
  Habit removeCompletedDate(DateTime date) {
    final normalizedDate = DateTime(date.year, date.month, date.day);
    
    final newCompletedDates = completedDates.where((d) => 
      !(d.year == normalizedDate.year && 
        d.month == normalizedDate.month && 
        d.day == normalizedDate.day)
    ).toList();
    
    return copyWith(completedDates: newCompletedDates);
  }

  // Convert to Map for database storage
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'description': description,
      'icon': icon,
      'colorValue': colorValue,
      'frequency': frequency,
      'amount': amount,
      'completedDates': completedDates.map((date) => date.toIso8601String()).toList(),
      'createdAt': createdAt.toIso8601String(),
      'reminderTimes': reminderTimes,
    };
  }

  // Create a Habit from a Map
  factory Habit.fromMap(Map<String, dynamic> map) {
    return Habit(
      id: map['id'],
      name: map['name'],
      description: map['description'] ?? '',
      icon: map['icon'] ?? 'list',
      colorValue: map['colorValue'] ?? 0xFF4A6572,
      frequency: map['frequency'] ?? '每天',
      amount: map['amount'] ?? '',
      completedDates: (map['completedDates'] as List?)
        ?.map((dateStr) => DateTime.parse(dateStr))
        ?.toList() ?? [],
      createdAt: DateTime.parse(map['createdAt']),
      reminderTimes: (map['reminderTimes'] as List?)
        ?.map((time) => time as String)
        ?.toList() ?? [],
    );
  }
}
